/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
 
/* $Id: convert.c 16 2007-06-10 02:10:04Z kf701.ye $ */

#include "kf701.h"

/**
 * @brief  reverse a byte
 * @param  temp  raw byte
 * @return reversed byte
 */
uint8_t reverse_char(uint8_t temp)
{
    int32_t j;
    uint8_t temp2 = 0;
    for( j=0; j<8; j++ )
    {
	temp2 = (temp2<<1);
	if( temp&0x01 )
	    temp2 |= 0x01;
	temp = temp>>1;
    }
    return temp2;
}

static inline uint8_t char2hex(uint8_t c)
{
	static const char *HexCharacters = "0123456789ABCDEF";
	if (c > 15)
	{
		sys_message("%s,%d: error\n",__FILE__,__LINE__);
		return 'R';
	}
	return HexCharacters[c];
}

/** 
 * @brief bin data to hex text
 *
 * dest length must be at least twice of src length
 *
 * @param dest output buffer
 * @param src  input buffer
 * @param len  length of src
 *
 * @return void
 */
void bin2hex(uint8_t *dest,const uint8_t *src, uint32_t len)
{
        uint8_t first;
        uint8_t second;
        while(len > 0)
        {
                first = *src / 0x10;
                second = *src % 0x10;
                *dest = char2hex(first);
                dest++;
                *dest = char2hex(second);
                dest++;
                len--;
                src++;
        }
}

static inline uint8_t hex2char(char c)
{
	if (c >= '0' && c <= '9')
		return c -'0';
	else
		return c -'A'+ 0x0A;
}

/** 
 * @brief hex text to bin data
 *
 * dest length must be at least half of src length
 *
 * @param dest output buffer
 * @param src  input buffer
 * @param len  length of src
 * @return void
 */
void hex2bin(uint8_t *dest,const uint8_t *src, uint32_t len)
{
	if (len%2 != 0)
	{
		sys_message("%s,%d: error\n",__FILE__,__LINE__);
		return;
	}
	while (len >0)
	{
		*dest = hex2char(*src)*0x10 + hex2char(*(src+1));
		src += 2;
		dest ++;
		len -= 2;
	}
	return;
}
